import type { NitroApp } from "nitropack";
import { Server as Engine } from "engine.io";
import { Server,type Socket as ServerSocket} from "socket.io";
import { isValidToken } from "../middleware/auth";

export var serverSocket:ServerSocket
const userSocketMap= new Map()
export const engine = new Engine();
export const io = new Server();

export default defineNitroPlugin((nitroApp: NitroApp) => {

  io.bind(engine as any);
  io.on("connection",  async (socket) => {
    serverSocket=socket
    const token = socket.handshake.query.token;
    let isValid = false;
    if(token){
     isValid=await isValidToken(token as string) as unknown as boolean
    }

    if (!isValid) {
      socket.disconnect(true);
      return;
    }
    userSocketMap.set(token,socket.id)
    // //所有人发送时间同步器
    socket.emit("getTime",Date.now())
    socket.on("index", (dataMsg,uId,gId) => {
      // redisClient.lpush("chat_history", JSON.stringify(msg));
      if(gId){
        socket.to(userSocketMap.get(gId)).emit("index", dataMsg);
      }else{
        //获取所有在线id出了他自己发给所有人发一份
        socket.broadcast.emit("index", dataMsg);
      }
    })
    socket.on("disconnect", () => {
    userSocketMap.delete(token); // 断开时清除记录‌:ml-citation{ref="6" data="citationList"}
    });
  });

  nitroApp.router.use("/socket.io/", defineEventHandler({
    handler(event) {
      engine.handleRequest(event.node.req, event.node.res);
      event._handled = true;
    },
    websocket: {
      open(peer) {
        const nodeContext = peer.ctx.node;
        const req = nodeContext.req;

        // @ts-expect-error private method
        engine.prepare(req);

        const rawSocket = nodeContext.req.socket;
        const websocket = nodeContext.ws;

        // @ts-expect-error private method
        engine.onWebSocket(req, rawSocket, websocket);
      }
    }
  }));
});